package kr.hyosang.dkbs.kiosk.widget;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javafx.application.Platform;
import javafx.scene.control.Label;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Pane;
import javafx.scene.layout.VBox;

import javax.imageio.ImageIO;

import kr.hyosang.dkbs.kiosk.factory.StyleFactory;
import kr.hyosang.util.NetManager;

import com.swetake.util.Qrcode;

public class Ticker extends WidgetBase {
	private Qrcode mQrcode;
	private Pane mMainPane;
	private Label mCate;
	private Label mTitle;
	private ImageView mQrcodeView;
	
	private ArrayList<NoticeInfo> mList = null;
	private int mNextIndex = 0;
	private Timer mTimer = null;
	
	
	public Ticker(Pane mainPane) {
		mMainPane = mainPane;
		
		init();
	}
	
	private void init() {
		HBox firstBox = new HBox();
		firstBox.setPrefWidth(mMainPane.getPrefWidth());
		
		ImageView dkuLogo = new ImageView();
		dkuLogo.setFitHeight(80);
		dkuLogo.setFitWidth(80);
		firstBox.getChildren().add(dkuLogo);
		
		VBox secondBox = new VBox();
		secondBox.setPrefWidth(mMainPane.getPrefWidth() - 80 - 80);
		mCate = new Label();
		mCate.setStyle(StyleFactory.getTickerCategoryStyle());
		secondBox.getChildren().add(mCate);
		
		mTitle = new Label();
		mTitle.setText("Notice list");
		mTitle.setStyle(StyleFactory.getTickerTitleStyle());
		secondBox.getChildren().add(mTitle);
		
		firstBox.getChildren().add(secondBox);
		
		mQrcodeView = new ImageView();
		mQrcodeView.setFitWidth(80);
		mQrcodeView.setFitHeight(80);
		firstBox.getChildren().add(mQrcodeView);
		
		mMainPane.getChildren().add(firstBox);
		
		mQrcode = new Qrcode();
		mQrcode.setQrcodeEncodeMode('B');
		mQrcode.setQrcodeErrorCorrect('M');
		mQrcode.setQrcodeVersion(0);
		
		mLoader.start();
		mTimer = new Timer();
		mTimer.schedule(new TimerTask() {
			@Override
			public void run() {
				Platform.runLater(mTickerDisplay);
			} }, 0, 10000);
	}
	
	private Runnable mTickerDisplay = new Runnable() {
		@Override
		public void run() {
			if(mList != null) {
				if(mNextIndex >= 0 && mNextIndex < mList.size()) {
					NoticeInfo info = mList.get(mNextIndex);
					
					mCate.setText(info.category);
					mTitle.setText(info.title);
					setQRCode(info.url, mQrcodeView);
				}
				
				mNextIndex = (++mNextIndex) % mList.size();
			}
		}
	};
	
	private Thread mLoader = new Thread() {
		public void run() {
			String content = NetManager.getWebContent("http://www.dankook.ac.kr/web/kor/d1_2");
			
			Pattern tbody = Pattern.compile("<tbody>(.*)</tbody>");
			Matcher tbodyM = tbody.matcher(content);
			
			if(tbodyM.find()) {
				String tbodyS = tbodyM.group(1);
				
				Pattern row = Pattern.compile("<tr>(.*?)</tr>");
				Matcher rowM = row.matcher(tbodyS);
				
				ArrayList<NoticeInfo> noticeList = new ArrayList<NoticeInfo>();
				
				while(rowM.find()) {
					String tr = rowM.group(1);
					Pattern cell = Pattern.compile("style=\"color:#[0-9A-Fa-f]{6}\">(.*)</font>.*<td class=\"subject\">[\\s]*<a href=\".*_EXT_BBS_messageId=([0-9]+)[^\\\"]*\".*?>(.*)</a>");
					Matcher cellM = cell.matcher(tr);
					
					if(cellM.find()) {
						String category = cellM.group(1);
						String url = cellM.group(2);
						String title = cellM.group(3);
						
						title = title.trim();
						category = category.replace("&gt;", ">");
						category = category.replaceAll("[\\s]*", " ").trim();
						
						NoticeInfo info = new NoticeInfo();
						info.category = category;
						info.title = title;
						info.url = String.format("http://www.dankook.ac.kr/web/kor/d1_2?p_p_id=EXT_BBS&_EXT_BBS_struts_action=%%2Fext%%2Fview_message&_EXT_BBS_messageId=%s", url);
						noticeList.add(info);
					}
				}
				
				mList = noticeList;
			}
		}
	};
	
	private void setQRCode(String url, ImageView iv) {
		try {
			url = "http://www.dankook.ac.kr/web/kor/d1_2";
			boolean [][] data = mQrcode.calQrcode(url.getBytes("UTF-8"));
			int multi = 2;
			int x = data.length;
			int y = data[0].length;
			int w = (x + 2) * multi;
			int h = (y + 2) * multi;
			
			BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_BGR);
			Graphics2D g = bi.createGraphics();
			g.setBackground(Color.WHITE);
			g.clearRect(0, 0, w, h);
			g.setColor(Color.BLACK);
			
			for(int i=0;i<x;i++) {
				for(int j=0;j<y;j++) {
					if(data[i][j]) g.fillRect((i+1)*multi, (j+1)*multi, multi, multi);
				}
			}
			
			g.dispose();
			bi.flush();
			
			ByteArrayOutputStream output = new ByteArrayOutputStream();
			
			ImageIO.write(bi, "jpg", output);
			
			iv.setImage(new Image(new ByteArrayInputStream(output.toByteArray())));
			
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}catch(IOException e) {
			e.printStackTrace();
		}
		
		
	}
	
	

	@Override
	protected String getTag() {
		return "Ticker";
	}
	
	private class NoticeInfo {
		public String category;
		public String title;
		public String url;
	}

}
